<?php
/**
 * 
 * @author Youssef Driouach
 *
 */
class Application_Model_TvMapper{

	protected $_dbTable;

	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}

	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_Tv');
		}
		return $this->_dbTable;
	}
	
	public function save(Application_Model_Tv $tv){
		
		
		$productMapper = new Application_Model_ProductMapper();
		$row = $productMapper->save($tv);
		//TODO set the object save function to return the id of the object saved
		//$where = array('model = ?' => (string)$product->getModel());
		$tv->setProductId($row);
		
		$data = array(
				'id_product' 	=> $tv->getProductId(),
				'type'			=> $tv->getType(),
				'threed'		=> $tv->getThreed(),
		);
		
		if (null === ($id = $tv->gettvId())) {
			unset($data['id_tv']);
			return $this->getDbTable()->insert($data);
		} else {
			$this->getDbTable()->update($data, array('id_tv = ?' => $id));
			return $id;
		}
	}
	
	public function find($id, Application_Model_Tv $tv)
	{
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$tv->setTvId($row->id_tv);
		$tv->setProductId($row->id_product);
		$tv->setType($row->type);
		$tv->setThreed($row->threed);
		
		$productMapper = new Application_Model_ProductMapper();
		$tv = $productMapper->find($tv->getProductId(), $tv);
	
		return $tv;
	}
	
	public function delete($id)
	{
	
		$tv= new Application_Model_Tv();
		$productMapper = new Application_Model_ProductMapper();
		$tv = $this->find($id, new Application_Model_Tv());
	
		$result = $this->getDbTable()->find($id);
		if (0 != count($result)) {
			$this->getDbTable()->delete(array('id_tv = ?' => $id));
		}
	
		$productMapper->delete($tv->getProductId());
	
	
	}
	
	public function indexBuilder(Zend_Search_Lucene_Document $doc, Application_Model_Tv $tv)
	{
		$productMapper = new Application_Model_ProductMapper();
		$requestBuilder = new Application_Model_Builder_Request();
		$doc->addField(Zend_Search_Lucene_Field::Text('type', $tv->getType(), 'utf-8'));
		$doc->addField(Zend_Search_Lucene_Field::Text('threed', $tv->getThreed(), 'utf-8'));
		$doc->addField(Zend_Search_Lucene_Field::Text('objectType', 'tv', 'utf-8'));
		$doc = $productMapper->indexBuilder($doc, $tv);
	
		return $doc;
	}
	
}